<template>
  <div class="firmware">
    <group class="tip">
      <cell title="重命名" :value="deviceName" is-link @click.native="deviceRenameModel" class="rename">
        <img slot="icon" src="../../assets/cigrImage/personal_center_rename.png" class="icon">
      </cell>
      <cell title="固件升级" :value="firmwareVersion" is-link @click.native="firmwareModel" :class="{point: upgradeVersion}">
        <img slot="icon" src="../../assets/cigrImage/personal_center_firmware.png" class="icon">
      </cell>
    </group>
    <group>
      <cell-box @click.native="unbindingModel" class="unbinding__cell-box">
        <div>解绑</div>
      </cell-box>
    </group>

    <!--重命名弹窗-->
    <div v-transfer-dom class="renameWindow">
      <confirm v-model="rename"
      :title="reNameTitle"
      @on-confirm="onConfirmRename">
        <x-input type="text" v-model.trim="deviceNewName" :placeholder="currentDevice.device_mac" class="borderStyle" :max="12"></x-input>
      </confirm>
    </div>

    <!--固件升级弹窗-->
    <div v-transfer-dom class="renameWindow">
      <confirm v-model="updateFirmware"
      :title="`发现新版本：${upgradeVersion}`"
      :content="upgradeDescription"
      @on-confirm="onConfirmUpgardFirmware">
      </confirm>
    </div>

    <!--解绑设备弹窗-->
    <div v-transfer-dom class="unbindingWindow">
      <confirm v-model="unbindingDevice"
      :title="unbindingCurrentDevice"
      @on-confirm="onConfirmDeviceUnbinding">
        <p>解绑设备后将无法使用手机控制，确定解绑此设备？</p>
      </confirm>
    </div>
  </div>
</template>
<script>
import api from '@/api'
import _ from 'lodash'
import wx from 'weixin-js-sdk'
import { Panel, Group, Cell, CellBox, XInput, Confirm, TransferDomDirective as TransferDom } from 'vux'

export default {
  name: 'Firmware',
  directives: {
    TransferDom
  },
  components: {
    Panel,
    Group,
    Cell,
    CellBox,
    XInput,
    Confirm
  },
  data () {
    return {
      name: 'HH-HH-HH-HH',
      // 重命名弹窗信息
      rename: false,
      reNameTitle: '重命名',
      deviceName: '',
      deviceNewName: '',

      // 固件
      updateFirmware: false,
      firmwareName: '5.52.256',
      upgradeVersion: '',
      upgradeTaskId: '',
      upgradeDescription: '',

      // 解绑弹窗信息
      unbindingDevice: false,
      unbindingCurrentDevice: '解绑设备',

      currentDevice: {
        device_id: 0,
        device_mac: '',
        device_name: '',
        device_pid: '',
        device_type: ''
      },
      firmwareVersion: ''
    }
  },
  mounted () {
    this.initialize()
  },
  computed: {
  },
  methods: {
    async initialize () {
      await this.fetchCurrentDevice()
      await this.getFirmwareUpgardeInfo()
    },

    // 设备重命名
    deviceRenameModel () {
      // 设备名name 是扩展属性，不存在的时候默认为mac
      this.deviceNewName = this.currentDevice.device_name ? this.currentDevice.device_name : this.currentDevice.device_mac
      this.rename = !this.rename
    },
    async onConfirmRename () {
      let uniqeName = _.some(this.devicesList, (device) => {
        return device.device_name === this.deviceNewName
      })
      if (!this.deviceNewName) {
        this.deviceNewName = this.currentDevice.device_mac
        uniqeName = false
      }
      if (!uniqeName) {
        await api.changeDeviceName(this.currentDevice.device_id, {'device_name': this.deviceNewName})
        this.fetchCurrentDevice()
      } else {
        alert('设备名已经使用，请重新命名')
      }
    },

    // 固件管理
    async firmwareModel () {
      this.updateFirmware = !this.updateFirmware
    },

    // 解绑设备
    unbindingModel () {
      this.unbindingDevice = !this.unbindingDevice
    },
    onConfirmDeviceUnbinding () {
      let currentDevice = this.currentDevice
      let deviceId = currentDevice.device_id
      wx.invoke('getWXDeviceTicket', {'deviceId': deviceId, 'type': 2}, async (res) => {
        await api.unbindingDevice(deviceId, res.ticket)
        let userId = window.localStorage.getItem('userId')
        await api.unsubscribe(userId, { 'device_id': deviceId })
        this.$router.go(-1)
      })
    },
    // 升级固件
    async onConfirmUpgardFirmware () {
      await api.startUpgarde({
        product_id: this.currentDevice.device_pid,
        upgrade_task_id: this.upgradeTaskId,
        status: 1
      })
    },

    // 获取当前设备和固件版本
    async fetchCurrentDevice () {
      let { data: {devices} } = await api.getDeviceList()
      this.devicesList = devices
      let currentDeviceId = this.$route.params.device_id
      this.currentDevice = _.filter(devices, (device) => {
        return device.device_id === currentDeviceId
      })[0]
      this.deviceName = this.currentDevice.device_name ? this.currentDevice.device_name : this.currentDevice.device_mac
      let { data: {firmware_version: firmwareVersion} } = await api.getDeviceInfo(this.currentDevice.device_pid, this.currentDevice.device_id)
      this.firmwareVersion = firmwareVersion
    },

    async getFirmwareUpgardeInfo () {
      let params = {
        product_id: this.currentDevice.device_pid,
        type: 1,
        current_version: 1,
        identify: 0
      }
      try {
        let {data: {id, description, target_version: targetVersion}} = await api.getFirmwareUpgardeInfo(this.currentDevice.device_id, params)
        this.upgradeTaskId = id
        this.upgradeVersion = targetVersion
        this.upgradeDescription = `<p style="text-align:left">更新日志：</p><p style="text-align:left">${description}</p>`
      } catch (err) {
        console.log(err)
      }
    }
  }
}
</script>
<style lang="stylus">
  .firmware {
    height: calc(100% - 10px);
    background-color: #ebebeb;
    padding-top: 10px; 
    .weui-cells {
      .weui-cell {
        padding: 15px 15px;
      }
      margin-top: 10px;
    }
    .tip {
      .weui-cells {
        .weui-cell {
          .icon {
            width: 30px;
            display:block;
            margin-right:14px;
          }
          &.point {
            .weui-cell__ft {
              position: relative;
              padding-right: 24px;
              &:before {
                content: url(../../assets/cigrImage/cigar_point.png);
                position: absolute;
                right: 20px;
                width: 5px;
                height: 5px;
                border-raduis: 50%;
              }
            }
          }
        }
        margin-top: 0px;
      }
    }
    .unbinding__cell-box {
      >div {
        width: 100%;
        text-align: center;
        color: #ff3b3f;
      }
    }
  }
  .renameWindow {
    .borderStyle {
      border: 1px solid #e3e3e3 !important;
      border-radius: 10px !important;
    }
  }
  @media only screen and (max-width: 320px){
    .tip {
      .rename {
        &.weui-cell {
          .weui-cell__ft {
            max-width: 180px;
            box-sizing: border-box;
            white-space: nowrap;
            text-overflow: ellipsis;
            overflow: hidden;
          }
        }
      }
    }
  }
</style>
